package com.example.lotterysystem.dao.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.example.lotterysystem.dao.dataobject.Encrypt;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Encrypt.class) // 被处理的类型
@MappedJdbcTypes(JdbcType.VARCHAR) // 处理后的 Jdbc类型
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {

    private final String key = "1234123412341234";
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Encrypt encrypt, JdbcType jdbcType) throws SQLException {
        if(encrypt == null || encrypt.getValue() == null){
            ps.setString(i, null);
            return;
        }
        // 加密
        AES aes = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8));
        String str = aes.encryptHex(encrypt.getValue());
        ps.setString(i, str);
    }

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return decrypt(resultSet.getString(s));
    }

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return decrypt(resultSet.getString(i));
    }

    @Override
    public Encrypt getNullableResult(CallableStatement cs, int i) throws SQLException {
        return decrypt(cs.getString(i));
    }

    private Encrypt decrypt(String string){
        if(!StringUtils.hasText(string)){
            return null;
        }
        return new Encrypt(SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8)).decryptStr(string));
    }
}
